package cn.iocoder.yudao.module.trade.config.controller.admin;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.trade.config.dal.dataobject.TradeConfigDO;
import cn.iocoder.yudao.module.trade.config.service.TradeConfigService;
import cn.iocoder.yudao.module.trade.config.vo.TradeConfigRespVO;
import cn.iocoder.yudao.module.trade.config.vo.TradeConfigSaveReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 交易中心配置")
@RestController
@RequestMapping("/trade/config")
@Validated
public class TradeConfigController {

    @Resource
    private TradeConfigService tradeConfigService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @RequestMapping(value = "/save", method = {RequestMethod.PUT, RequestMethod.POST})
    @Operation(summary = "更新交易中心配置")
    @PreAuthorize("@ss.hasRole('shop_admin')")
    public CommonResult<Boolean> updateConfig(@Valid @RequestBody TradeConfigSaveReqVO updateReqVO) {
        Long shopId = shopInfoApi.getShopIdByAdminUserId(getLoginUserId());
        tradeConfigService.saveTradeConfig(shopId, updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得交易中心配置")
    @PreAuthorize("@ss.hasPermission('trade:config:query')")
    public CommonResult<TradeConfigRespVO> getConfig(@RequestParam(value = "id", required = false) Long id) {
        TradeConfigDO config;
        if (id != null && id > 0) {
            config = tradeConfigService.getTradeConfigById(id);
        } else {
            Long shopId = shopInfoApi.getShopIdByAdminUserId(getLoginUserId());
            config = tradeConfigService.getOrCreateTradeConfigByShopId(shopId);
        }
        TradeConfigRespVO configVO = BeanUtils.toBean(config, TradeConfigRespVO.class);
        return success(configVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获得交易中心配置列表")
    @PreAuthorize("@ss.hasPermission('trade:config:query')")
    public CommonResult<List<TradeConfigRespVO>> getConfigList() {
        List<TradeConfigDO> config = tradeConfigService.getTradeConfigList();
        List<TradeConfigRespVO> respVOS = BeanUtils.toBean(config, TradeConfigRespVO.class);
        return success(respVOS);
    }

}
